<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\SuningApiLog;
use GuzzleHttp\Client;
use App\Common\Common;
use Exception;
use App\Jobs\SyncSuning;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Order;

class SuningTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SuningTest';
    protected $timeout = 10;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Command description";

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {          
        // $this->queryServiceRange();
        $this->queryAttributeInformation();
        // $this->suningLbQuerypriceCreate();
        // $this->suningLbCreateorderCreate();
        // $this->suningLbOrderupdateCreate();
        // $this->suningLbInquiryorderCreate();
        // $this->suningLbMessageCreate();

        return 0;
    }

    /**
     * 3.4.1 商户查询订购的商品和品牌信息
     * 通过帮客系统签订合同后，可通过接口查询合同中订购的商品和品牌信息
     */
    public function queryServiceRange()
    {
        $method = 'query.service.range';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id')
        ];
        $content = $this->GetSuningApiContent($method, $data);
        $resultObj = json_decode($content);
        if (!$resultObj->data) {
          return 0;  
        } 
        if ($resultObj->data->customerService) {
            foreach($resultObj->data->customerService as $customerService) {
                //if (in_array($customerService->extdCmmdtyCtgry, ['R2301003', 'R2101001', 'R9007124', 'R9010411'])) {
                    var_dump($customerService);
                    // Cache::put('suning_service_' . $customerService->extdCmmdtyCtgry);
                //}
                $this->info($customerService->extdCommodityName ."\t". $customerService->extdCmmdtyCtgry);
            }
        } 
        if ($resultObj->data->brandInfo) {
            foreach($resultObj->data->brandInfo as $brandInfo) {
                $this->info($brandInfo->brandCode ."\t". $brandInfo->brandDesc);
            }
        }

        
        return 0;
    }

    /**
     * 3.4.2 商户查询商品关联的属性信息
     * 
     */
    public function queryAttributeInformation()
    {
        // $extdCmmdtyCtgry = 'R0301003';
        $extdCmmdtyCtgry = 'R9007124';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'extdCmmdtyCtgry' => $extdCmmdtyCtgry
        ];
        $method = 'query.attribute.information';
        $content = $this->GetSuningApiContent($method, $data);
        $this->info($content);
        $resultObj = json_decode($content);
        if (!$resultObj->data) {
          return 0;  
        } 
        if ($resultObj->data->data) {
            foreach($resultObj->data->data as $property) {
                $this->info($property->propFieldCode ."\t". $property->propFieldDesc);
            }
        } 
        return 0;
    }

    /**
     * 3.4.3 直连商户订单下发ASMP
     * 商户将订单信息通过调用此接口发送给苏宁平台
     */
    function suningLbCreateorderCreate()
    {
        $serial_number = Common::GetSerialNumber();

        $name = '陈圣无';
        $mobile = '13311180920';

        $order = Order::create([
            'serial_number' => $serial_number,
            'user_id' => 1, 
            // 'coupon_code' => $request->input('coupon_code'),
            'name' => $name,
            'phone' => $mobile,
            'province' => '北京',
            'city' => '北京',
            'district' => '朝阳区',
            'street' => '劲松三区甲302',
            'home' => '华腾大厦1808',
            'remark' => '',
            'status' => 1,
        ]);


        $method = 'suning.lb.createorder.create';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'sourceOrderItemId' => Common::GetSerialNumber(), //商家系统订单号
            'consignee' => $name, //顾客姓名
            'mobPhoneNum' => $mobile, //移动电话
            'phoneNum' => '', //固定电话
            'province' => '北京',
            'city' => '北京',
            'area' => '朝阳区',
            'street' => '劲松三区甲302',
            'address' => '华腾大厦2508', //详细地址
            'cityCode' => '010',
            'srvAreaCode' => '0100516',
            'cmmdtyQaType' => '1', //质保标识 0：保内；1：保外
            'extdCmmdtyBand' => '000281762',
            'extdCmmdtyCtgry' => 'R9010411', //苏宁商品编码
            'extdCommodityName' => '家庭保洁', //苏宁商品名称
            'brandCode' => '1762', //苏宁品牌编码
            'orderTime' => date("YmdHis"),
            'proName' => '08', //作业项目
            'saleDate' => date("Ymd"),
            'saleQty' => '1', //服务数量
            'serviceTime' => date("YmdHis", strtotime('+2days')), //预约时间
            'propertyCode' => (object)[], //商品属性集合?
            'srvMemo' => '测试订单' //服务订单备注?
        ];

        Log::info(json_encode($data));
        $method = 'suning.lb.createorder.create';
        $content = $this->GetSuningApiContent($method, $data);
        Log::info($content);

        $resultObj = json_decode($content, true);
        if ($resultObj && isset($resultObj['success']) && $resultObj['success'] == true) {
            if (isset($resultObj['data']) && isset($resultObj['data']['salesOrder'])) {
                $order->provider_order_id = $resultObj['data']['salesOrder'];
                $order->save();
            }
        }
        return 0;
    }

    /**
     * 3.4.4 直连商户订单信息修改通知ASMP
     * 商户将订单修改信息通过调用此接口反馈给苏宁平台
     */
    function suningLbOrderupdateCreate()
    {
        $method = 'suning.lb.orderupdate.create';
        $data = [
            'vendorCode' => config('app.suning.id'), //商家编码
            'salesOrder' => 'MP768874656463980301', //ASMP服务订单号
            'updateMode' => '02', //修改类型 01：修改 02：取消
            'srvNote' => '临时有事', //修改/取消原因
            // 'serviceTime' => '', //服务预约时间
            // 'operateUser' => '' //帮客联保账号?
        ];
        $content = $this->GetSuningApiContent($method, $data);
        $this->info($content);
        return 0;
    }

    /**
     * 3.4.6 直连商户主动查询订单作业信息接口
     * 商户通过调用此接口至苏宁平台主动查询订单作业信息
     */
    function suningLbInquiryorderCreate()
    {
        $method = 'suning.lb.inquiryorder.create';
        $data = [
            'vendorCode' => config('app.suning.id'),
            'salesOrder' => 'MP675061355560986201', //ASMP服务单号
            'srvOrder' => '201116174313j7CaTdtEOfBe' //服务订单号
        ];
        SyncSuning::dispatch($method, $data);
        return 0;
    }

    /**
     * 3.4.12 商户将留言信息通知苏宁
     * 商户将留言信息通过调用此接口反馈给苏宁平台
     */
    function suningLbMessageCreate()
    {
        $method = 'suning.lb.message.create';
        $data = [
            'vendorCode' => config('app.suning.id'),
            'srvOrder' => 'MP675624292154875901', //服务订单号
            'lwContent' => '这是一条测试留言信息。。。', //留言信息
            'crateTime' => date('Y-m-d H:i:s')
        ];
        $this->info(json_encode($data));
        SyncSuning::dispatch($method, $data);
        return 0;
    }

    /**
     * 3.4.14 查ASMP定价
     * 通过接口查询该商品的价格信息
     * 
     * 示例数据：
     * "extdCmmdtyCtgry": "R9010391",
     * "buDesc": "售后事业部",
     * "buCode": "00028",
     * "proName": "08",
     * "extdCommodityName": "家庭开荒保洁",
     * "proNameDesc": "上门清洗"
     * 
     */
    function suningLbQuerypriceCreate()
    {
        $this->error(config('app.suning.id'));
        $method = 'suning.lb.queryprice.create';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'extdCmmdtyCtgry' => 'R9010391',  // 苏宁商品编码
            'brandCode' => '1762', // 苏宁品牌编码
            'proName' => '08', //作业项目
            'saleQty' => '1', //服务数量
            'propertyCode' => (object)[]
        ];
        $this->info(json_encode($data));
        
        SyncSuning::dispatch($method, $data);
           
        return 0;
    }

    /**
     * 对苏宁接口请求的封装
     * 
     * @return Object
     */
    public function GetSuningApiContent(string $method, array $data)
    {
        $client = new Client();
        $dataStr = json_encode($data);
        $sign = Common::SuningSign($method, $dataStr, config('app.suning.app_key'), config('app.suning.app_secret'));
        $fullUrl = Common::SuningUrl(config('app.suning.url'), $method, config('app.suning.app_key'), $sign);
        $resp_status = 0;
        $resp_content = '';
        try {
            $response = $client->request('POST', $fullUrl, [
                'body' => $dataStr,
                'timeout' => $this->timeout
            ]);
            $resp_status = $response->getStatusCode();
            if ($resp_status == 200) {
                $resp_content = $response->getBody()->getContents();
            }
            
        } catch (Exception $e) {
            throw $e;
        } finally {
            // 记录调用日志
            SuningApiLog::create([
                'from' => 'SuningTestCommand',
                'req_url' => config('app.suning.url'),
                'req_method' => 'POST',
                'req_param' => json_encode([
                    'method' => $method,
                    'app_key' => config('app.suning.app_key'),
                    'sign' => $sign
                ]),
                'req_body' => $dataStr,
                'resp_status' => $resp_status,
                'resp_body' => $resp_content
            ]);
        }

        return $resp_content;
    }
}
